
import React, { useState, useEffect, useRef } from 'react';
import { Button, View, Platform, ToastAndroid, BackHandler, Text } from 'react-native';
import 'react-native-get-random-values';
import { WebView } from "react-native-webview"

let canBack = false


const WebviewScreen = (state) => {
  const [url, setUrl] = useState('')
  const [initUrl, setInitUrl] = useState('')
  const [lastBackPressed, setLastBackPressed] = useState(0)

  const bindWebView = useRef(); //绑定ref

  let onBackAndroid = () => {
    if (canBack) { // false,表示webView中没有返回事件，为true则表示该webView有回退事件
      bindWebView.current.goBack()
      return true;
    } else return false;
  }
  const onNavigationStateChange = navState => {
    if (initUrl && navState.url.indexOf('http') == -1) { //节流
      if (lastBackPressed && lastBackPressed + 500 >= Date.now()) {
        state.navigation.goBack()
        return false;
      }
      setLastBackPressed(Date.now())
      return
    }
    if (navState.url != initUrl && (navState.url.indexOf('http') > -1 && !initUrl)) setInitUrl(navState.url)
    canBack = navState.canGoBack
    state.navigation.setOptions({ title: navState.url })

  };


  useEffect(() => {
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', onBackAndroid);
    }
    state.navigation.setOptions({ headerShown: false })
    setUrl(state.route.params.url)
    return () => {  //页面销毁
      BackHandler.removeEventListener(
        'hardwareBackPress',
        onBackAndroid,
      );
    }
  }, []);

  return (
    <WebView ref={bindWebView} onNavigationStateChange={onNavigationStateChange} source={{ uri: url }}></WebView>
  );


}



export default WebviewScreen;